package ofpof.domain.dao;

import java.util.Date;

import ofpof.database.MongoDatabaseConnectionProvider;
import ofpof.domain.Session;
import ofpof.domain.dao.mapper.SessionMapper;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

@Repository
public class SessionDao {
	
	@Autowired
	private MongoDatabaseConnectionProvider connectionProvider;

	@Autowired
	private SessionMapper sessionMapper;

	public void create(Session session) {
		session.setId(new ObjectId());
		session.setCreatedOn(new Date());
	
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection sessionCollection = connection.getCollection("session");
		
		DBObject dbObject = sessionMapper.toDbObject(session);
		sessionCollection.insert(dbObject);
	}

	public void update(Session session) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection sessionCollection = connection.getCollection("session");
		DBObject dbObject = sessionMapper.toDbObject(session);
		sessionCollection.update(new BasicDBObject("_id",session.getId()),dbObject);
	}

	public Session findById(ObjectId sessionId) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection sessionCollection = connection.getCollection("session");
		DBObject dbObject = sessionCollection.findOne(new BasicDBObject("_id",sessionId));
		if (dbObject != null) {
			return sessionMapper.fromDbObject(dbObject);
		}
		
		return null;
	}

	public void deleteOlderThan(Date boundaryDate) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection sessionCollection = connection.getCollection("session");
		
		DBObject query = new BasicDBObject();
		query.put("createdon", new BasicDBObject("$lte",boundaryDate));
		sessionCollection.remove(query);
	}

	public void deleteById(ObjectId sessionId) {
		DB connection = connectionProvider.getCurrentConnection();
		DBCollection sessionCollection = connection.getCollection("session");
		
		DBObject query = new BasicDBObject("_id",sessionId);
		sessionCollection.remove(query);
	}

}
